package apollo.generator.common.base;

import org.springframework.util.StringUtils;

/**
 * <Description>
 * 响应工具类
 * @author Jun Lee
 * @version 1.0
 * @createDate 2020-03-27 18:15:36
 */
public class RR extends R {

    private static ThreadLocal<R> responseThreadLocal = new ThreadLocal();

    private RR() {
        super();
    }

    public static R fail() {
        R instance = R.getInstance();
        instance.setCode(IBaseResponseCode.ERROR_CODE).setMsg(IBaseResponseCode.ERROR_MESSAGE)
                    .setStatus(IBaseResponseCode.ERROR_STATUS);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R fail(String message) {
        R instance = R.getInstance();
        instance.setCode(IBaseResponseCode.ERROR_CODE).setMsg(message)
                .setStatus(IBaseResponseCode.ERROR_STATUS);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R success() {
        R instance = R.getInstance();
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R success(String msg) {
        R instance = R.getInstance();
        instance.setMsg(msg);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R success(Object object) {
        R instance = R.getInstance();
        if (StringUtils.isEmpty(object)) {
            instance.setMsg(IBaseResponseCode.NOT_FOUND_DATA);
        }else{
            instance.setData(object);
        }
        responseThreadLocal.set(instance);
        return instance;
    }


//    public static R success2Rename(Object object,String name) throws NoSuchFieldException, IllegalAccessException {
//        R<Object> instance = new R(name);
//        instance.setData(object);
//        responseThreadLocal.set(instance);
//        return instance;
//    }


    public static R isOperation(boolean isSuccess) {
        R instance = R.getInstance();
        if (isSuccess) {
            instance.setMsg(IBaseResponseCode.OPERATION_SUCCESS);
        } else {
            instance.setMsg(IBaseResponseCode.OPERATION_FAILED).setCode(IBaseResponseCode.ERROR_CODE)
                    .setStatus(IBaseResponseCode.ERROR_STATUS);
        }
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R customize(Integer code, String message) {
        return customize(code,message,null);
    }


    public static R customize(Integer code, String message, Object object) {
        R instance = R.getInstance();
        instance.setCode(code).setMsg(message).setData(object);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R get() {
        return (R)responseThreadLocal.get();
    }

    public static void remove() {
        responseThreadLocal.remove();
    }

    public static Kmap build(){
        return new Kmap();
    }
}
